﻿using System.Threading;

namespace AhpilyServer
{
    /// <summary>
    /// 一个需要执行的方法
    /// </summary>
    public delegate void ExecuteDelegate();


    
    /// <summary>
    /// 单线程池
    /// </summary>
    public class SingleExecute
    {
        private static SingleExecute instance;

        /// <summary>
        /// 用于单例
        /// </summary>
        private static object lockFlag = 1;
        /// <summary>
        /// 单例
        /// </summary>
        public static SingleExecute Instance
        {
            get
            {
                lock(lockFlag)
                {
                    if(instance == null)
                    {
                        instance = new SingleExecute();
                    }
                    return instance;
                }

            }
        }

        /// <summary>
        /// 互斥锁
        /// </summary>
        private readonly Mutex mutex;

        private SingleExecute()
        {
            mutex = new Mutex();
        }

        /// <summary>
        /// 单线程处理逻辑
        /// </summary>
        /// <param name="executeDelegate"></param>
        public void Execute(ExecuteDelegate executeDelegate)
        {
            lock(this)
            {
                mutex.WaitOne();
                executeDelegate();
                mutex.ReleaseMutex();
            }
        }
    }
}
